<?php
include_once 'application/application.php';

class Page_contacts {

    private $cnt_table = 'admin_contact_list';

    public $action;
    public $error;



    public function __construct() {
        $this->action = Arr::getValue($_POST, 'action', false);

        DB::connect();
        if (!DB::state()) {
            $this->error = DB::getError();
        }
    }

    public function __destruct() {

    }



    public function ratingUpdate() {
        $params = array();
        $J = new JSON();

        $params['action'] = $J->readVar('action');
        $params['id']     = (int)$J->readVar('id',0);

        if (!Auth::isLogged()) return $J->error('not_logged');
        if (!$params['id']) {
            return $J->error('no_id');
        }

        $res = DB::query("SELECT rating FROM `{$this->cnt_table}` WHERE id = {$params['id']}");
        if (!$res || !DB::state()) return $J->error('db_select_err');

        $row = mysqli_fetch_array($res, MYSQLI_ASSOC);
        $rating = Arr::getValue($row, 'rating', NULL);
        $params['old_value'] = $rating;

        if (is_null($rating)) return $J->error('not_found');

        if ($params['action'] == ACTIONS::CONTACT_RATING_DEC) {
            if ($rating > -5) $rating--;
            else return $J->error('dec_denied');
        }
        else if ($params['action'] == ACTIONS::CONTACT_RATING_INC) {
            if ($rating < 5) $rating++;
            else return $J->error('inc_denied');
        }


        $res = DB::query("UPDATE `{$this->cnt_table}` SET rating = {$rating} WHERE id = {$params['id']}");
        if (!$res || !DB::state()) return $J->error('db_update_err');


        $J->new_rating = $rating;
        $params['new_value'] = $rating;

        if (class_exists('Log')) Log::Save(OPERATION::UPDATE_CONTACT_RAT, $params);

        return $J;

    }


    function contactRead(&$J) {
        $params = array();

        $_POST['id'] = Arr::getValue($_POST, 'cnt_id', 0);

        $params['action']       = $J->readVar('action');
        $params['id']           = (int)$J->readVar('id',0);
        $params['firstname']    = mysql_escape_string($J->readVar('firstname'));
        $params['lastname']     = mysql_escape_string($J->readVar('lastname'));
        $params['middlename']   = mysql_escape_string($J->readVar('middlename'));
        $params['gender']       = mysql_escape_string($J->readVar('gender',0));
        $params['mail']         = mysql_escape_string($J->readVar('mail'));
        $params['im']           = mysql_escape_string($J->readVar('im'));
        $params['job']          = mysql_escape_string($J->readVar('job'));
        $params['phone']        = mysql_escape_string($J->readVar('phone'));

        if ($params['gender'] == 'f') $params['gender'] = 0;
        else if ($params['gender'] == 'm') $params['gender'] = 1;
        else $params['gender'] = -1;

        return $params;
    }


    public function checkFields($params) {
        $wrongFields = array();


        $name = 'firstname';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;

        $name = 'lastname';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;

        $name = 'gender';
        $var = $params[$name];
        $msg = '';
        if (!$msg && ($var == -1)) $msg = 'Не заполнено обязательное поле';
        if (!$msg && !in_array($var, array(0,1))) $msg = 'Некорректное значение';
        if ($msg) $wrongFields[$name] = $msg;


        $name = 'job';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;

        $name = 'phone';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;

        $name = 'mail';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;

        $name = 'im';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;


        return $wrongFields;

    }



    public function contactAdd() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');

        $params = $this->contactRead($J);
        $wrongFields = $this->checkFields($params);

        if (count($wrongFields)) {
            $J->wrongFields = $wrongFields;
            return $J;
        }

        $q = "INSERT INTO `{$this->cnt_table}`
                           (`id`,   `firstname`,              `lastname`,              `middlename`,              `gender`,              `im`,              `job`,              `mail`,              `phone`              )
                    VALUES (NULL,   '{$params['firstname']}', '{$params['lastname']}', '{$params['middlename']}', '{$params['gender']}', '{$params['im']}', '{$params['job']}', '{$params['mail']}', '{$params['phone']}' )";
        $res = DB::query($q);
        if (!$res || !DB::state()) {
            $J->error('Ошибка при сохранении данных <!--('.DB::$mysqli->error.')-->');
            return $J;
        }

        $J->insertedId = DB::$mysqli->insert_id;

        $params['id'] = $J->insertedId;
        if (class_exists('Log')) Log::Save(OPERATION::CREATE_CONTACT, $params);

        return $J;

    }

    public function contactUpdate() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');

        $params = $this->contactRead($J);
        $wrongFields = $this->checkFields($params);

        if (count($wrongFields)) {
            $J->wrongFields = $wrongFields;
            return $J;
        }

        $contacts = getAllContacts(); // array('byId'=>array(), 'byFio'=>array());
        if (!DB::$lastReqState) return $J->error('Не удалось получить список контактов <!--'.DB::getError().'-->');

        $contacts = Arr::getValue($contacts, 'byId', array());
        $old_val = Arr::getValue($contacts, $params['id'], false);
        if (!is_array($old_val)) return $J->error('Этот контакт не существует');




        $q = "UPDATE `{$this->cnt_table}`
              SET
                    `firstname` = '{$params['firstname']}',
                    `lastname` = '{$params['lastname']}',
                    `middlename` = '{$params['middlename']}',
                    `gender` = '{$params['gender']}',
                    `im` = '{$params['im']}',
                    `job` = '{$params['job']}',
                    `mail` = '{$params['mail']}',
                    `phone` = '{$params['phone']}'
              WHERE id = {$params['id']}";

        $res = DB::query($q);
        if (!$res || !DB::state()) {
            $J->error('Ошибка при сохранении данных <!--('.DB::$mysqli->error.')-->');
            return $J;
        }

        $J->insertedId = DB::$mysqli->insert_id;
        if (class_exists('Log')) Log::Save(OPERATION::UPDATE_CONTACT, array('old_value'=>$old_val, 'new_value'=>$params, 'id'=>$params['id']));

        return $J;


    }




    public function itemList() {
        //if ($this->error) $this->printOut ($this->error);

        $params = getAllContacts(); // array('byId'=>array(), 'byFio'=>array());
        if (!DB::$lastReqState) $this->error = 'Невозможно получить список контактов <!--'.DB::getError().'-->';


        $params['error'] = $this->error;

        echo includeFile(APP_PAGE_PARTS.'list_contacts.php', $params);
    }


    public function outPage() {
        $params = array();

        $this->printOut(includeFile(APP_PAGE_PARTS.'page_contacts.php', $params));
    }




    public function printOut( $content = '' ) {

        include_once APP_PAGE_PARTS.'header.php';
        echo Navbar::getHorisontalBar();
        echo Auth::loginForm(true);

        $params = array(
            'leftmenu'  => Navbar::getVerticalBar('leftmenu'),//includeFile(APP_PAGE_PARTS.'leftmenu.php'),
            'content'   => $content? $content : ''
        );
        include APP_PAGE_PARTS.'columns.php';

        include_once APP_PAGE_PARTS.'footer.php';
        die();
    }



}

$page = new Page_contacts();

if ($page->action) {
    if ($page->action == ACTIONS::CONTACT_RATING_DEC)   echo $page->ratingUpdate();
    if ($page->action == ACTIONS::CONTACT_RATING_INC)   echo $page->ratingUpdate();
    if ($page->action == ACTIONS::CONTACT_NEW)          echo $page->contactAdd();
    if ($page->action == ACTIONS::CONTACT_UPDATE)       echo $page->contactUpdate();
}
else  {
    if (array_key_exists('getList', $_REQUEST)) {
        if (!Auth::isLogged()) inlineReLocate ('index.php');
        else $page->itemList();
    }
    else {
        if (!Auth::isLogged()) reLocate ('index.php');

        Navbar::$expanded = 'lm-internal';
        Navbar::$active = 'list_contacts';
        $page->outPage();
    }




}
?>